/** @file    DialogLoadBundle.cpp
 *  @author  Alessandro Polo
 *  @version $Id: DialogCreateGui.cpp 2808 2010-07-28 20:44:00Z alex $
 *  @brief
 * File containing methods for the wosh::gui::DialogLoadBundle class.
 * The header for this class can be found in DialogLoadBundle.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
 #include "DialogCreateGui.h"
 #include "ui_DialogCreateGui.h"

 #include <framework/gui/dialogs/GuiDialogs.h>
 #include <core/ObjectFactory.h>
 #include <core/Request.h>
 #include <core/Response.h>
 #include <core/List.h>
 #include <core/WoshKernel.h>
 #include <core/MethodsCommon.h>

 #include <QtGui>


using namespace std;
namespace wosh {
 namespace gui {

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

DialogCreateGui::DialogCreateGui( QWidget *parent )
	: QDialog(parent), IWidget() {
	this->m_ui = new Ui::DialogCreateGui();
	this->m_ui->setupUi(this);

	setWindowTitle( tr("Create GUI for..") );
	this->myURI.setName( Utilities::format("DialogCreateGui#%10lu", getClassName(), Utilities::randomLong()) );
	this->myURI.setKernelLocal();

	this->getTargetURI().setAny();
	QObject::connect(this->m_ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	QObject::connect(this->m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
//	QObject::connect(this->m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(doReset()));

	this->m_ui->wUpBarAutoDetect->getUpdateButton()->setText( tr("Auto-Detect Interfaces") );
	QObject::connect(this->m_ui->wUpBarAutoDetect, SIGNAL(updateClicked()), this, SLOT(doAutoDetect()));
//	QObject::connect(this->m_ui->btnRemove, SIGNAL(clicked()), this, SLOT(btnRemove_clicked()));
//	QObject::connect(this->m_ui->cmbType, SIGNAL(editTextChanged(const QString&)), this, SLOT(txtType_editTextChanged(const QString&)));


	QObject::connect(this->m_ui->wTargetUri, SIGNAL(changedURI(const URI&)), this, SLOT(changedURI(const URI&)));

	// tab Local object
	this->sand_obj = NULL;
	this->serializable_types_model = new ObjectTypeInfoListModel(this);
	this->m_ui->cmbSandObjectType->setModel(this->serializable_types_model);

	this->gui_types_model = new ObjectTypeInfoTableModel(this);
	this->m_ui->tableViewInterfaces->setModel(this->gui_types_model);
	connect(this->m_ui->cmbSandObjectType, SIGNAL(currentIndexChanged(int)), this, SLOT(cmbSandObjectType_currentIndexChanged(int)));

	connect(this->m_ui->tBtnObjectTypesRefresh, SIGNAL(clicked()), this, SLOT(refreshObjectTypeList()));
	connect(this->m_ui->btnSandObjectAllocate, SIGNAL(clicked()), this, SLOT(btnSandObjectAllocate_clicked()));
	connect(this->m_ui->btnSandObjectDestroy, SIGNAL(clicked()), this, SLOT(btnSandObjectDestroy_clicked()));


	refreshObjectTypeList();
	setMode(DialogCreateGui::DIALOG_MIXED);
 }

DialogCreateGui::~DialogCreateGui() {
	delete this->m_ui;

	if ( this->sand_obj != NULL ) {
		ObjectFactory::destroy(this->sand_obj);
		this->sand_obj = NULL;
	 }

 }

void DialogCreateGui::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::refreshAll() {

	refreshObjectTypeList();
 }

void DialogCreateGui::refreshObjectTypeList() {
	this->serializable_types_model->getData().clear();
	WRESULT ret = ObjectFactory::findChildsOf( this->serializable_types_model->getData(), "wosh::ISerializable", 0.0, true );
	if ( WFAILED(ret) ) {
		QMessageBox::critical(this, tr("Listing Serializable types.."), tr("FAILED. Error#%1 gathering list.").arg(ret) );
	 }
	this->serializable_types_model->reset();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::setMode( DIALOG_MODE mode ) {
	this->m_ui->tabLocalObject->setEnabled(false);
	this->m_ui->tabRemoteObject->setEnabled(false);

	if ( mode == DialogCreateGui::DIALOG_MIXED ) {
		this->m_ui->tabLocalObject->setEnabled(true);
		this->m_ui->tabRemoteObject->setEnabled(true);
		return;
	 }

	this->m_ui->tabWidget->setCurrentIndex((int)mode);
	this->m_ui->tabWidget->widget((int)mode)->setEnabled(true);

 }

void DialogCreateGui::doReset() {
 }


//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::setTargetURI( const URI& uri ) {
	if (  getTargetURI().isValid() && getTargetURI() != uri ) {
		this->m_ui->wUpBarAutoDetect->showError(tr("Disaligned URI, click Auto-Detect to reflesh interfaces."));
	 }
	IWidget::setTargetURI(uri);
	this->m_ui->wTargetUri->setTargetURI(uri);
 }

void DialogCreateGui::changedURI( const URI& uri ) {
	if ( getTargetURI() != uri ) {
		this->m_ui->wUpBarAutoDetect->showError(tr("Disaligned URI, click Auto-Detect to reflesh interfaces."));
	 }
	IWidget::setTargetURI(uri);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::doAutoDetect() {
	if ( this->m_ui->chkRemote_RequestInterfaces->isChecked() )
		postMessageForTarget( new Message(new Request(_METHOD_ListInterfaces)) );
	if ( this->m_ui->chkRemote_RequestObjectInfo->isChecked() ) {
		List* props = new List(2);
		props->push_back<Variant>(_KEY_name);
		props->push_back<Variant>(_KEY_type);
		postMessageForTarget( new Message(new Request(_METHOD_GetProperties, props)) );
	 }
	this->m_ui->wUpBarAutoDetect->sayRetrieving();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::configureForObjectType( const char* class_name, double , bool update_combo ) {
	this->gui_types_model->getData().clear();
	this->gui_types_model->reset();

	if ( this->sand_obj == NULL )
		this->m_ui->lblSandObjectStatus->setText( tr("Status: IDLE (object not allocated)") );
	else
		this->m_ui->lblSandObjectStatus->setText( tr("Status: DISALIGNED! (allocated object %1)").arg(this->sand_obj->getClassName()) );

	if ( class_name == NULL ) {
		if ( update_combo )
			this->m_ui->cmbSandObjectType->setCurrentIndex(-1);
		return;
	 }
	ObjectTypeInfo info = GuiUtilities::findGuiFor(class_name);
	this->gui_types_model->getData().push_back(info);
	this->gui_types_model->reset();

	if ( this->sand_obj == NULL )
		return;

	if ( this->sand_obj->isClass(class_name) ) {
		this->m_ui->lblSandObjectStatus->setText( tr("Status: ALIGNED (allocated object %1)").arg(this->sand_obj->getClassName()) );
	 }
	else {
		this->m_ui->lblSandObjectStatus->setText( tr("Status: DISALIGNED! (allocated object %1, instead of %2)").arg(this->sand_obj->getClassName()).arg(class_name) );
	 }

 }

void DialogCreateGui::setupForLocalObject( ISerializable* obj ) {
	if ( this->sand_obj != NULL ) {
		WRESULT ret = ObjectFactory::destroy(this->sand_obj); (void)ret;
		this->sand_obj = NULL;
//		this->m_ui->lblSandObjectStatus->setText( tr("Status: IDLE (object not allocated)") );
	 }
	this->sand_obj = obj;
	if ( obj != NULL ) {
		this->m_ui->lblSandObjectStatus->setText( tr("Status: Allocated %1 (acquired instance)").arg(this->sand_obj->getClassName()) );
		configureForObjectType( this->sand_obj->getClassName() );
	 }
	else
		configureForObjectType(NULL);
 }

void DialogCreateGui::setupForLocalObject( const ISerializable* obj ) {
	if ( this->sand_obj != NULL ) {
		WRESULT ret = ObjectFactory::destroy(this->sand_obj);
		this->sand_obj = NULL;
		if ( WFAILED(ret) )
			QMessageBox::critical(this, tr("Destroy SandObject.."), tr("FAILED. Error#%1 destroying object.").arg(ret) );
	 }

	if ( obj == NULL ) {
		this->sand_obj = NULL;
		this->m_ui->lblSandObjectStatus->setText( tr("Status: IDLE (object not allocated)") );
		configureForObjectType(NULL);
	 }
	else {
		this->sand_obj = obj->clone();
		this->m_ui->lblSandObjectStatus->setText( tr("Status: Allocated %1 (instance copy)").arg(this->sand_obj->getClassName()) );
		configureForObjectType( this->sand_obj->getClassName() );
	 }

 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::cmbSandObjectType_currentIndexChanged( int ) {
	configureForObjectType( this->m_ui->cmbSandObjectType->currentText().toLatin1().data(), 0.0, false );
 }

void DialogCreateGui::btnSandObjectAllocate_clicked() {
	if ( this->sand_obj != NULL ) {
		QMessageBox::warning(this, tr("Allocate SandObject.."), tr("FAILED. Destroy current object before allocating a new one.") );
		return;
	 }
	ISerializable* obj = ObjectFactory::createTypeOf<ISerializable>( this->m_ui->cmbSandObjectType->currentText().toStdString(), 0.0);
	if ( obj == NULL ) {
		QMessageBox::critical(this, tr("Allocate SandObject.."), tr("FAILED. Unable to allocate object!") );
		this->m_ui->lblSandObjectStatus->setText( tr("Status: IDLE") );
		return;
	 }
	setupForLocalObject( obj );
 }

void DialogCreateGui::btnSandObjectDestroy_clicked() {
	if ( this->sand_obj == NULL ) {
		QMessageBox::warning(this, tr("Destroy SandObject.."), tr("FAILED. No allocated object found.") );
		return;
	 }
	setupForLocalObject( (ISerializable*)NULL );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::buildInterfacesList() {
/*	this->itemInterfaces.clear();
	QListWidgetItem* item = NULL;
	for(int i=0; i<this->m_ui->wDataListInterfaces->count(); i++) {
		item = this->m_ui->wDataListInterfaces->item(i);
		if ( item == NULL ) continue;
		this->itemInterfaces.append( item->text() );
	 }
*/
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void DialogCreateGui::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() ) return;
	if ( !URI::pregMatch( this->myURI, message.getDestination() ) ) return;
	if ( !message.getContent()->isResponse() ) return;
	const wosh::Response* response = message.getContent()->asResponse();
	if ( !response->hasData() ) return;

	if ( response->getMethod() == _METHOD_ListInterfaces ) {
		if ( response->getData()->isKindOf<Table>() ) {
	//		this->m_ui->tableViewInterfaces->loadObject( response->getData()->as<Table>() );
			this->m_ui->wUpBarAutoDetect->sayReady();
		 }
		else
			this->m_ui->wUpBarAutoDetect->showError(tr("Unrecognized data format [%1]").arg(response->getData()->getClassName()));
	 }
	else if ( response->getMethod() == _METHOD_GetProperty ) {
		if ( !response->getData()->isKindOf<Property>() )
			return;
		const wosh::Property* propName = response->getData()->as<Property>();
		if ( propName->getKey() == _KEY_name ) {
			this->itemName = propName->getValue().toString();
		 }
		else if ( propName->getKey() == _KEY_type ) {
			this->itemType = propName->getValue().toString();
//			this->m_ui->cmbType->setEditText( this->itemType.c_str() );
		 }
		this->m_ui->wUpBarAutoDetect->sayReady();
	 }

 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
